package com.shbaiche.bifenba.util;

import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseUI;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.match.EaseRegisterMessage;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;

import okhttp3.Call;

/**
 * Created by Administrator on 2018/8/29 0029.
 */

public class UserUtil {
    public void register() {
        EaseRegisterMessage message = new EaseRegisterMessage();
        message.setPassport(App.getPassport());
        message.setUniqueCode(SystemUtil.getUniquePsuedoID());

        NetApi.easeRegister(message, new JsonCallback<TransMessage>() {
            @Override
            public void onFail(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onResponse(TransMessage response, int id) {
                EaseRegisterMessage result =new Gson().fromJson(response.getMessage(),EaseRegisterMessage.class);
                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, result.getCode())) {
                    if(result!=null && result.getUserName()!=null){
                        App.mBBSName = result.getUserName();
                        login(result.getUserName(),result.getPassword());
                    }
                }else{
                    ToastUtil.show(response.getMessage());
                }
            }
        });
    }



    private void login(final String userName, String password){
        try {
            EMClient.getInstance().login(userName,password,new EMCallBack() {//回调
                @Override
                public void onSuccess() {
                    EMClient.getInstance().groupManager().loadAllGroups();
                    EMClient.getInstance().chatManager().loadAllConversations();
                    Log.d("main", "登录聊天服务器成功！");
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {
                    Log.d("main", "登录聊天服务器失败！"+message);

                    Message msg= new Message();
                    msg.what = 1;
                    msg.obj =  "登录聊天服务器失败！"+message;

                }
            });
        }catch (Exception e){

        }catch (Error e){

        }

    }
}
